package cn.edu.lzzy.controllers.course;

import cn.edu.lzzy.entities.Allocation;
import cn.edu.lzzy.entities.Messages;
import cn.edu.lzzy.services.AllocationService;
import cn.edu.lzzy.utils.AuthUtils;
import cn.edu.lzzy.utils.Name;
import cn.edu.lzzy.utils.StringUtils;
import cn.edu.lzzy.vm.JSONResult;
import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;

//import org.h2.util.json.JSONArray;
//import org.h2.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import springfox.documentation.oas.annotations.EnableOpenApi;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@EnableOpenApi
@Tag(name = "authorize-api-controller",description ="用户授权认证接口")
@RequestMapping(value = "/authorize")
public class AuthorizeApiController {
    private final AllocationService service;
    private final WebApplicationContext context;
    /**获取权限 * /
     *
     */
    @GetMapping(value = "/urls")
    public JSONResult getUrls(@RequestParam String token){
        //Map主要用于表示key/Value
        List<Map<String ,Object>> list=new ArrayList<>();
        List<String> urls=new ArrayList<>();
        List<Allocation> allocations=service.finAll();
        RequestMappingHandlerMapping mappingHandlerMapping=context.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodMap=mappingHandlerMapping.getHandlerMethods();
        for(Map.Entry<RequestMappingInfo,HandlerMethod> entry:mappingInfoHandlerMethodMap.entrySet()){

            Map<String ,Object> item=new HashMap<>(16);
            RequestMappingInfo info=entry.getKey();
            HandlerMethod method=entry.getValue();
            if(!method.hasMethodAnnotation(Name.class))
            {
                continue;
            }
            PatternsRequestCondition condition=info.getPatternsCondition();
            if(condition==null){
                continue;
            }
            for (String url:condition.getDirectPaths()){
                item.put("url",url);
            }
        String url=item.get("url").toString();
         Allocation allocation=allocations.stream().filter(x->x.getUrl().equals(url)).findAny().orElse(null);
         urls.add(url);

         Name name=method.getMethod().getDeclaringClass().getAnnotation(Name.class);

         String controllerName=
                 name==null?method.getMethod().getDeclaringClass().getName():name.name();
         item.put("controller",controllerName);
         String m=method.getMethod().getName();
         item.put("method",m);
         String methodName=method.getMethod().getAnnotation(Name.class).name();
         item.put("methodName",methodName);
         int value= AuthUtils.getDefaultAuthValue();
         item.put("value",value);
         list.add(item);
        }
        service.sysUrls(urls);
        return new JSONResult(200,list,list.size()+"");

    }
    /**** 获取用户类型 */
    @Autowired
    public AuthorizeApiController(AllocationService service,WebApplicationContext context){
 this.service=service;
 this.context=context;
    }

    @GetMapping(value = "/types")
    public JSONResult getUserTypes(@RequestParam String token){
        return new JSONResult(200, service.getUserTypes(),Messages.SUCCESS.toString());
    }

    private int getModuleValue(JSONArray array, int size){
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<size;i++){
            if(i>=array.size()){
                builder.append("1");
            }else{
                builder.append(array.getIntValue(i));
            }
        }
        return AuthUtils.getAuthValue(builder.toString());
    }
    /**获取权限分配*/
    public JSONResult allocate(@RequestBody JSONObject json){
        String token=json.getString("token");
        if(StringUtils.isEmpty(token)){
            return new JSONResult(403,"没有相关权限", Messages.LOGIN_FAIL_INFO.toString());

        }
        JSONArray modules =json.getJSONArray("modules");
        if(modules==null){
            return new JSONResult(4033,"没有相关权限",Messages.NO_PERMISSION.toString());

        }
        List<Allocation> allocations=new ArrayList<>();
        int size=service.getUserTypes().size();
        for(int i=0;i<modules.size();i++){

            JSONObject ob=modules.getJSONObject(i);
            String url=ob.getString("url");

            JSONArray array=ob.getJSONArray("values");
            int val=getModuleValue(array,size);
            Allocation allocation=service.save(url,val);
            allocations.add(allocation);
        }
        return new JSONResult(200,allocations,"分配了"+allocations.size());
    }
}
